<template>
  <VueOfficeExcel v-if="type == 'xlsx'" :src="file" style="height: 100%" @rendered="rendered" />
  <VueOfficeDocx v-if="type == 'docx'" :src="file" style="height: 100%" @rendered="rendered" />
  <VueOfficePdf v-if="type == 'pdf'" :src="file" style="height: 100%" @rendered="rendered" />
</template>

<script setup lang="ts">
  import { useRoute } from 'vue-router';
  import '@vue-office/docx/lib/index.css';
  import '@vue-office/excel/lib/index.css';
  import VueOfficeDocx from '@vue-office/docx';
  import VueOfficePdf from '@vue-office/pdf';
  import VueOfficeExcel from '@vue-office/excel';
  const route = useRoute();
  const file = ref();
  const type = ref<string>('');
  const props = defineProps({
    urlAction: {
      type: String,
    },
    type: {
      type: String,
    },
  });
  watch(
    props,
    (value) => {
      if (value.urlAction && value.type) {
        type.value = props.type as string;
        fetch(`${props.urlAction}`, {
          method: 'get',
        }).then((res) => {
          if (res.status == 200) {
            //读取文件的arrayBuffer
            res.arrayBuffer().then((res) => {
              file.value = res;
            });
          } else {
            file.value = value.urlAction as string;
          }
        });
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );
  // 后端返回的二进制文件流
  watch(
    route,
    (value) => {
      if (value.query.url) {
        if (!value.query.type || value.query.type == '') {
          ElMessage.error('缺少参数！');
          return;
        }
        type.value = value.query.type as string;
        fetch(`${value.query.url}`, {
          method: 'get',
        }).then((res) => {
          if (res.status == 200) {
            //读取文件的arrayBuffer
            res.arrayBuffer().then((res) => {
              file.value = res;
            });
          } else {
            file.value = value.query.url;
          }
        });
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );
  const rendered = () => {
    ElMessage.success('渲染完成！');
  };
  // const errorHandler = () => {
  //   ElMessage.error('渲染失败，请刷新！');
  // };
</script>

<style lang="scss" scoped></style>
